package com.gxpt.app.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnItemLongClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.interfaces.OnRefreshListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.recyclerview.ProgressStyle;
import com.google.gson.Gson;
import com.gxpt.app.AppUtils;
import com.gxpt.app.BaseFragment;
import com.gxpt.app.Constant;
import com.gxpt.app.MessageEvent;
import com.gxpt.app.R;
import com.gxpt.app.adapter.newlist_Adapter;
import com.gxpt.app.bean.iconlist_bean;
import com.gxpt.app.bean.newlist_bean;
import com.gxpt.app.view.Activity_life_need_detail;
import com.gxpt.app.view.Activity_services_types_list;
import com.squareup.picasso.Picasso;
import com.utils.T;
import com.utils.logger.Logger;
import com.utils.okhttputils.HttpUtils;
import com.utils.picasso.CircleTransform;
import com.zhy.http.okhttp.callback.StringCallback;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;

/**
 * Created by dufeng on 2017/9/8.
 */

@ContentView(R.layout.fragment_home_life)
public class Fragment_home_life extends BaseFragment {



    Context context;
    /**服务器端一共多少条数据*/
    private static final int TOTAL_COUNTER = 10000;//如果服务器没有返回总数据或者总页数，这里设置为最大值比如10000，什么时候没有数据了根据接口返回判断

    /**每一页展示多少条数据*/
    private static final int REQUEST_COUNT = 20;

    /**已经获取到多少条数据了*/
    private static int mCurrentCounter = 0;

    private newlist_Adapter mDataAdapter = null;


    private LRecyclerViewAdapter mLRecyclerViewAdapter = null;

    ///////////////////
    int page_num  = 1;
    int page_size = 20;

    @ViewInject(R.id.mLRecyclerView)
    LRecyclerView mLRecyclerView;




    private View topView;




//    @ViewInject(R.id.type1)
    ImageView type1;
//    @ViewInject(R.id.type2)
    ImageView type2;
//    @ViewInject(R.id.type3)
    ImageView type3;
//    @ViewInject(R.id.type4)
    ImageView type4;
//    @ViewInject(R.id.type5)
    ImageView type5;
//    @ViewInject(R.id.type6)
    ImageView type6;
//    @ViewInject(R.id.type7)
    ImageView type7;
//    @ViewInject(R.id.type8)
    ImageView type8;

//    @ViewInject(R.id.txt1)
    TextView txt1;
//    @ViewInject(R.id.txt2)
    TextView txt2;
//    @ViewInject(R.id.txt3)
    TextView txt3;
//    @ViewInject(R.id.txt4)
    TextView txt4;
//    @ViewInject(R.id.txt5)
    TextView txt5;
//    @ViewInject(R.id.txt6)
    TextView txt6;
//    @ViewInject(R.id.txt7)
    TextView txt7;
//    @ViewInject(R.id.txt8)
    TextView txt8;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
//        Logger.i("注册成功");
        EventBus.getDefault().register(this);
    }

    @Override
    public void onDestroyView() {
        EventBus.getDefault().unregister(this);
        super.onDestroyView();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMoonEvent(MessageEvent messageEvent){
         if(messageEvent.getMessage().equals(Constant.ACTION_TO_CHANGECITY)){
            mDataAdapter.clear();
            mLRecyclerViewAdapter.notifyDataSetChanged();//fix bug:crapped or attached views may not be recycled. isScrap:false isAttached:true
            mCurrentCounter = 0;
            do_Refresh();
        }

    }

    @Override
    public void onAttach(Context context) {
        this.context = context;
        super.onAttach(context);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View rootView = x.view().inject(this, inflater, container);
        initViews();
        initData();
        return  rootView;
    }

    private  void initViews(){
        initTopView();

        mDataAdapter = new newlist_Adapter(context);
        mLRecyclerViewAdapter = new LRecyclerViewAdapter(mDataAdapter);
        mLRecyclerView.setAdapter(mLRecyclerViewAdapter);

//        DividerDecoration divider = new DividerDecoration.Builder(this)
//                .setHeight(R.dimen.default_divider_height)
//                .setPadding(R.dimen.default_divider_padding)
//                .setColorResource(R.color.split)
//                .build();

        mLRecyclerView.setLayoutManager(new LinearLayoutManager(context));

        mLRecyclerView.setRefreshProgressStyle(ProgressStyle.LineSpinFadeLoader);
        mLRecyclerView.setArrowImageView(R.drawable.ic_pulltorefresh_arrow);
        mLRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallSpinFadeLoader);

        //add a HeaderView
        mLRecyclerViewAdapter.addHeaderView(topView);
        mLRecyclerView.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                mDataAdapter.clear();
                mLRecyclerViewAdapter.notifyDataSetChanged();//fix bug:crapped or attached views may not be recycled. isScrap:false isAttached:true
                mCurrentCounter = 0;
                do_Refresh();
            }
        });

        //是否禁用自动加载更多功能,false为禁用, 默认开启自动加载更多功能

        mLRecyclerView.setLoadMoreEnabled(true);

        mLRecyclerView.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                do_LoadMore();
            }
        });

        //设置头部加载颜色
        mLRecyclerView.setHeaderViewColor(R.color.red, R.color.red ,android.R.color.white);
        //设置底部加载颜色
        mLRecyclerView.setFooterViewColor(R.color.red, R.color.red ,android.R.color.white);
        //设置底部加载文字提示
        mLRecyclerView.setFooterViewHint("拼命加载中","已经全部为你呈现了","网络不给力啊，点击再试一次吧");

        mLRecyclerView.refresh();

        mLRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
                if (mDataAdapter.getDataList().size() > position) {
                    newlist_bean.newlist item = mDataAdapter.getDataList().get(position);
//
//                    Logger.i("item.id = "+item.id);
//

                    Intent gonew =new Intent();
                    gonew.setClass(context,Activity_life_need_detail.class);
                    gonew.putExtra("ID",item.id);
                    startActivity(gonew);
//                    Logger.i("item.id = "+item.id);
                }

            }

        });

        mLRecyclerViewAdapter.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public void onItemLongClick(View view, int position) {
//                ItemModel item = mDataAdapter.getDataList().get(position);
//                T.show(getApplicationContext(), "onItemLongClick - " + item.title,1);
            }
        });
    }

    private void do_Refresh(){
        page_num = 1;
        toNet_iconlist();//图标
        toNet_newlist();//最新
    }

    private void do_LoadMore(){
        page_num += 1;
        toNet_newlist();//最新
    }
    private void notifyDataSetChanged() {
        mLRecyclerViewAdapter.notifyDataSetChanged();
    }

    private void addItems(ArrayList<newlist_bean.newlist> list) {

        mDataAdapter.addAll(list);
        mCurrentCounter += list.size();
    }



    private void initTopView(){
        topView = LayoutInflater.from(context).inflate(R.layout.item_home_life_area,null, false);
        topView.setLayoutParams(new LRecyclerView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,ViewGroup.LayoutParams.WRAP_CONTENT));
        type1 = (ImageView) topView.findViewById(R.id.type1);
        type2 = (ImageView) topView.findViewById(R.id.type2);
        type3 = (ImageView) topView.findViewById(R.id.type3);
        type4 = (ImageView) topView.findViewById(R.id.type4);
        type5 = (ImageView) topView.findViewById(R.id.type5);
        type6 = (ImageView) topView.findViewById(R.id.type6);
        type7 = (ImageView) topView.findViewById(R.id.type7);
        type8 = (ImageView) topView.findViewById(R.id.type8);

        txt1  = (TextView) topView.findViewById(R.id.txt1);
        txt2  = (TextView) topView.findViewById(R.id.txt2);
        txt3  = (TextView) topView.findViewById(R.id.txt3);
        txt4  = (TextView) topView.findViewById(R.id.txt4);
        txt5  = (TextView) topView.findViewById(R.id.txt5);
        txt6  = (TextView) topView.findViewById(R.id.txt6);
        txt7  = (TextView) topView.findViewById(R.id.txt7);
        txt8  = (TextView) topView.findViewById(R.id.txt8);
    }


    private void initData(){
//        toNet_iconlist();//图标
//        toNet_newlist();//最新
    }

    private void setData_Icons(List<iconlist_bean.iconlist> icons){
        if(icons != null){
            for(int a=0;a<icons.size();a++){
                if(a==0){
                    if(icons.get(0).img_url.isEmpty()){
                        Picasso.with(context).load(R.mipmap.ic_launcher_round).resize(120, 120).transform(new CircleTransform()).into(type1);
                    }else{
                        Picasso.with(context).load(Constant.IP+"/"+icons.get(0).img_url).resize(120, 120).transform(new CircleTransform()).into(type1);
                    }
                    txt1.setText(icons.get(0).name);
                    txt1.setTag(Integer.parseInt(icons.get(0).link_url));
                    type1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle d = new Bundle();
                            d.putString("TITLE",txt1.getText().toString());
                            d.putString("TYPES_MAIN_ID",""+(int)txt1.getTag());

                            Intent goList = new Intent();
                            goList.setClass(context,Activity_services_types_list.class);
                            goList.putExtra("DATA",d);
                            startActivity(goList);

                        }
                    });
                }

                if(a==1){
                    if(icons.get(1).img_url.isEmpty()){
                        Picasso.with(context).load(R.mipmap.ic_launcher_round).resize(120, 120).transform(new CircleTransform()).into(type2);
                    }else{
                        Picasso.with(context).load(Constant.IP+"/"+icons.get(1).img_url).resize(120, 120).transform(new CircleTransform()).into(type2);
                    }
                    txt2.setText(icons.get(1).name);
                    txt2.setTag(Integer.parseInt(icons.get(1).link_url));
                    type2.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle d = new Bundle();
                            d.putString("TITLE",txt2.getText().toString());
                            d.putString("TYPES_MAIN_ID",""+(int)txt2.getTag());

                            Intent goList = new Intent();
                            goList.setClass(context,Activity_services_types_list.class);
                            goList.putExtra("DATA",d);
                            startActivity(goList);

                        }
                    });
                }

                if(a==2){
                    if(icons.get(2).img_url.isEmpty()){
                        Picasso.with(context).load(R.mipmap.ic_launcher_round).resize(120, 120).transform(new CircleTransform()).into(type3);
                    }else{
                        Picasso.with(context).load(Constant.IP+"/"+icons.get(2).img_url).resize(120, 120).transform(new CircleTransform()).into(type3);
                    }
                    txt3.setText(icons.get(2).name);
                    txt3.setTag(Integer.parseInt(icons.get(2).link_url));
                    type3.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle d = new Bundle();
                            d.putString("TITLE",txt3.getText().toString());
                            d.putString("TYPES_MAIN_ID",""+(int)txt3.getTag());

                            Intent goList = new Intent();
                            goList.setClass(context,Activity_services_types_list.class);
                            goList.putExtra("DATA",d);
                            startActivity(goList);

                        }
                    });
                }

                if(a==3){
                    if(icons.get(3).img_url.isEmpty()){
                        Picasso.with(context).load(R.mipmap.ic_launcher_round).resize(120, 120).transform(new CircleTransform()).into(type4);
                    }else{
                        Picasso.with(context).load(Constant.IP+"/"+icons.get(3).img_url).resize(120, 120).transform(new CircleTransform()).into(type4);
                    }
                    txt4.setText(icons.get(3).name);
                    txt4.setTag(Integer.parseInt(icons.get(3).link_url));
                    type4.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle d = new Bundle();
                            d.putString("TITLE",txt4.getText().toString());
                            d.putString("TYPES_MAIN_ID",""+(int)txt4.getTag());

                            Intent goList = new Intent();
                            goList.setClass(context,Activity_services_types_list.class);
                            goList.putExtra("DATA",d);
                            startActivity(goList);

                        }
                    });
                }

                if(a==4){
                    if(icons.get(4).img_url.isEmpty()){
                        Picasso.with(context).load(R.mipmap.ic_launcher_round).resize(120, 120).transform(new CircleTransform()).into(type5);
                    }else{
                        Picasso.with(context).load(Constant.IP+"/"+icons.get(4).img_url).resize(120, 120).transform(new CircleTransform()).into(type5);
                    }
                    txt5.setText(icons.get(4).name);
                    txt5.setTag(Integer.parseInt(icons.get(4).link_url));
                    type5.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle d = new Bundle();
                            d.putString("TITLE",txt5.getText().toString());
                            d.putString("TYPES_MAIN_ID",""+(int)txt5.getTag());

                            Intent goList = new Intent();
                            goList.setClass(context,Activity_services_types_list.class);
                            goList.putExtra("DATA",d);
                            startActivity(goList);

                        }
                    });
                }

                if(a==5){
                    if(icons.get(5).img_url.isEmpty()){
                        Picasso.with(context).load(R.mipmap.ic_launcher_round).resize(120, 120).transform(new CircleTransform()).into(type6);
                    }else{
                        Picasso.with(context).load(Constant.IP+"/"+icons.get(5).img_url).resize(120, 120).transform(new CircleTransform()).into(type6);
                    }
                    txt6.setText(icons.get(5).name);
                    txt6.setTag(Integer.parseInt(icons.get(5).link_url));
                    type6.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle d = new Bundle();
                            d.putString("TITLE",txt6.getText().toString());
                            d.putString("TYPES_MAIN_ID",""+(int)txt6.getTag());

                            Intent goList = new Intent();
                            goList.setClass(context,Activity_services_types_list.class);
                            goList.putExtra("DATA",d);
                            startActivity(goList);

                        }
                    });
                }

                if(a==6){
                    if(icons.get(6).img_url.isEmpty()){
                        Picasso.with(context).load(R.mipmap.ic_launcher_round).resize(120, 120).transform(new CircleTransform()).into(type7);
                    }else{
                        Picasso.with(context).load(Constant.IP+"/"+icons.get(6).img_url).resize(120, 120).transform(new CircleTransform()).into(type7);
                    }
                    txt7.setText(icons.get(6).name);
                    txt7.setTag(Integer.parseInt(icons.get(6).link_url));
                    type7.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle d = new Bundle();
                            d.putString("TITLE",txt7.getText().toString());
                            d.putString("TYPES_MAIN_ID",""+(int)txt7.getTag());

                            Intent goList = new Intent();
                            goList.setClass(context,Activity_services_types_list.class);
                            goList.putExtra("DATA",d);
                            startActivity(goList);

                        }
                    });
                }

                if(a==7){
                    if(icons.get(7).img_url.isEmpty()){
                        Picasso.with(context).load(R.mipmap.ic_launcher_round).resize(120, 120).transform(new CircleTransform()).into(type8);
                    }else{
                        Picasso.with(context).load(Constant.IP+"/"+icons.get(7).img_url).resize(120, 120).transform(new CircleTransform()).into(type8);
                    }
                    txt8.setText(icons.get(7).name);
                    txt8.setTag(Integer.parseInt(icons.get(7).link_url));
                    type8.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Bundle d = new Bundle();
                            d.putString("TITLE",txt8.getText().toString());
                            d.putString("TYPES_MAIN_ID",""+(int)txt8.getTag());

                            Intent goList = new Intent();
                            goList.setClass(context,Activity_services_types_list.class);
                            goList.putExtra("DATA",d);
                            startActivity(goList);

                        }
                    });
                }
            }
        }
    }

//    private void init_List_data(List<newlist_bean.newlist> d){
//
//        if(d == null)   return;
//        if(d.size()<=0) return;
//
//        mainListLayout.removeAllViews();
//        for (int a = 0; a < d.size(); a++) {
//            mainListLayout.addView(creatListItemView(d.get(a), d.get(a).id));
//        }
//    }
//
//    private View creatListItemView(newlist_bean.newlist d, int id) {
//        View convertView = LayoutInflater.from(context).inflate(R.layout.item_home_life_list, null);
//
//        TextView list_title = (TextView)convertView.findViewById(R.id.list_title);
//        list_title.setText(d.title);
//
//        TextView list_city_name = (TextView)convertView.findViewById(R.id.list_city_name);
//        list_city_name.setText(d.city_name);
//
//        TextView list_project_amount = (TextView)convertView.findViewById(R.id.list_project_amount);
//        list_project_amount.setText(d.project_amount);
//        list_project_amount.append(getString(R.string.txt_yuan));
//
//        ImageView pic_url= (ImageView)convertView.findViewById(R.id.list_pic);
//        if(d.file_url.isEmpty()){
//            PicassoUtils.Picasso_displayImage(context,R.mipmap.ic_launcher,pic_view_width,pic_view_hight,pic_url);
//        }else{
//            PicassoUtils.Picasso_displayImage(context,Constant.IP+"/"+d.file_url,pic_view_width,pic_view_hight,pic_url);
//        }
//
//        convertView.setId(id);
//        convertView.setOnClickListener(new View.OnClickListener(){
//
//            @Override
//            public void onClick(View v) {
////                int ViewID = v.getId();
//////                T.show(context,"ViewID = "+ViewID,1);
////
////                Intent goDetail = new Intent(context,Activity_web_detail.class);
////                goDetail.putExtra("ID",   ""+ViewID);
////                goDetail.putExtra("TYPE", Constant.HOT);
////                goDetail.putExtra("STATE","0");
////                startActivity(goDetail);
//
//
//            }
//        });
//        return convertView;
//    }

//    @Event(value={R.id.submenu0,R.id.submenu1,R.id.submenu2})
//    private void getEvent(View view){
//        switch(view.getId()){
//
//            case R.id.submenu0:
//                if(index != 0){
//                    index = 0 ;
//                    changeMenuView();
//                }
//
//
//                break;
//            case R.id.submenu1:
//                if(index != 1){
//                    index = 1 ;
//                    changeMenuView();
//                }
//
//
//                break;
//            case R.id.submenu2:
//                if(index != 2){
//                    index = 2 ;
//                    changeMenuView();
//                }
//
//
//                break;
//
//        }
//    }

    //////NET DO
    StringCallback do_iconlist = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
//            Logger.e(e.getMessage());
        }

        @Override
        public void onResponse(String s, int i) {
            if(hud.isShowing()){
                hud.dismiss();
            }
//            Logger.e(s);
            try{
                iconlist_bean data = new Gson().fromJson(s, iconlist_bean.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
                    setData_Icons(data.data);
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };

    StringCallback do_newlist = new StringCallback(){


        @Override
        public void onError(Call call, Exception e, int i) {
//            Logger.e(e.getMessage());
            mLRecyclerView.refreshComplete(REQUEST_COUNT);
        }

        @Override
        public void onResponse(String s, int i) {
            mLRecyclerView.refreshComplete(REQUEST_COUNT);
            if(hud.isShowing()){
                hud.dismiss();
            }
//            Logger.e("生活信息"+s);
            try{
                newlist_bean data = new Gson().fromJson(s, newlist_bean.class);
                if(data.state !=1 ){
                    T.show(context,data.msg,0);
                }else{
//                    if(data.data != null){
//                        if(data.data.size()>0){
//                            init_List_data(data.data);
//                        }
//                    }

                    if(data.data != null){
                        if(data.data.size()>0){
                            addItems((ArrayList)data.data);
                            notifyDataSetChanged();


                        }else{
                            page_num -= 1;
                        }
                    }
                }
            }catch (Exception e){
                e.printStackTrace();
                T.show(context,getResources().getString(R.string.alert_again),0);
            }
        }
    };
    /////NET
    private void toNet_iconlist(){
        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "homepage");
            jsonBody.put("serviceName",          "iconlist");

            jsonBody.put("type",                 1);
            jsonBody.put("page_num",             1);
            jsonBody.put("page_size",            8);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        HttpUtils.http_post_string(Constant.URL_iconlist,jsonBody.toString(),do_iconlist);
    }

    private void toNet_newlist(){
        hud.show();
        JSONObject jsonBody=new JSONObject();
        try {
            jsonBody.put("device_number",         AppUtils.get_device_id(context));
            jsonBody.put("device_type",           Constant.device_type);
            jsonBody.put("token",                 AppUtils.get_token(context));
            jsonBody.put("pageName",             "homepage");
            jsonBody.put("serviceName",          "newlist");

            jsonBody.put("area_id",               AppUtils.get_area_sub_id(context));
            jsonBody.put("page_num",             page_num);
            jsonBody.put("page_size",            page_size);
        } catch (JSONException e) {
            e.printStackTrace();
        }
//        Logger.i("toNet_newlist = "+jsonBody.toString());
        HttpUtils.http_post_string(Constant.URL_newlist,jsonBody.toString(),do_newlist);
    }


}
